package org.james.deleter.utils;

import java.io.File;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

import org.james.deleter.components.InfoListBox;

import application.Main;
import javafx.application.Platform;

public class FileOperater {

	public static void deleteFileByExtensions(String folderPath,String extensions){
		File folder = new File(folderPath);
		extensions = StringUtils.replace(extensions, " ", "");
		String[] extensionArr = StringUtils.split(extensions,"|");
		
		if(extensionArr.length > 0){
			List<String> extensionList = Arrays.stream(extensionArr).map(e -> e.substring(1))
					   .collect(Collectors.toList());
			deleteFilesRecursive(folder,extensionList);
		}
		InfoListBox.addMessageInfo("执行完毕");
		Platform.runLater(()-> {
			Main.execBtn.setText("确定");
			Main.execBtn.setDisable(false);
		});
		
	}
	
	public static void deleteFilesRecursive(File file,List<String> extensionList){
		if(file.isDirectory()){
			File[] files = file.listFiles();
			Arrays.stream(files).parallel().forEach((f) -> {
				deleteFilesRecursive(f,extensionList);
			});
		}else{
			String e = FileUtils.getFileExtension(file.getName());
			String path = file.getAbsolutePath();
			if(StringUtils.isNotBlank(e)){
				if(StringUtils.equalAny(e, extensionList.toArray(new String[]{}))){
					file.delete();
					InfoListBox.addMessageInfo("删除文件成功："+path);
				}
			}
		}
		
	}
	
}
